package com.example.mo.allfind.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.example.mo.allfind.R;
import com.example.mo.allfind.ui.callback.HeadCallBack;
import com.example.mo.allfind.ui.persional.AboutUsActivity;
import com.example.mo.allfind.ui.persional.ModifyInfoActivity;
import com.example.mo.allfind.ui.persional.OperatGuideActivity;
import com.example.mo.allfind.ui.persional.SettingActivity;
import com.example.mo.allfind.ui.persional.YouhuiActivity;
import com.example.mo.allfind.util.App;
import com.example.mo.allfind.util.CircleImageView;
import com.example.mo.allfind.util.HttpDownload;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.ButterKnife;


public class PersionalActivity extends AppCompatActivity implements HeadCallBack {

    private LinearLayout persionalInfo,other;
    private LinearLayout myyouhui, about_us, setting, operat_guide;
    private TextView common_title_bar_left, tv_title,name,sex,city;
    private CircleImageView headImg;
    private Bitmap head = null;
    private PhotoView photoView;
    private Info info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_persional);
        ButterKnife.bind(this);
        init();
        onClick();
        //Picasso.with(this).load(App.user.getUrl()).error(R.mipmap.ic_launcher).into(headImg);
        //上次下载的图片路径不存在或者与本次头像链接不一致，则下载
        if(App.user.getTempDownloadUrl() == null || !App.user.getTempDownloadUrl().equals(App.URL)){
            HttpDownload download = new HttpDownload(this);
            download.download(App.user.getUrl(),this);
            App.user.setTempDownloadUrl(App.user.getUrl());
        }else{
            name.setText("昵称:"+App.user.getNickname());
            sex.setText("性别:"+App.user.getSex());
            city.setText("城市:"+App.user.getCity());
            //先从本地读，如果没有，则去网络，如果没有，就设置默认图片
            head = BitmapFactory.decodeFile(App.IMAGE_FILE_PATH + "head.jpg");// 从SD卡中找头像，转换成Bitmap
            if(head != null){
                headImg.setImageBitmap(head);
            }else{
                //去服务器读
                Resources r = this.getResources();
                head = BitmapFactory.decodeResource(r, R.mipmap.ic_launcher);
                headImg.setImageBitmap(head);
            }
        }

    }
    private void onClick() {
        persionalInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent(PersionalActivity.this, ModifyInfoActivity.class);
                it.putExtra("name",name.getText().toString().trim());
                startActivityForResult(it,10);
            }
        });
        myyouhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(PersionalActivity.this, YouhuiActivity.class);
                startActivity(it);
            }
        });
        about_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(PersionalActivity.this, AboutUsActivity.class);
                startActivity(it);
            }
        });
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(PersionalActivity.this, SettingActivity.class);
                startActivity(it);
            }
        });
        operat_guide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(PersionalActivity.this, OperatGuideActivity.class);
                startActivity(it);
            }
        });
        common_title_bar_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        n
        headImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTypeDialog();
            }
        });
        photoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photoView.animaTo(info, new Runnable() {
                    @Override
                    public void run() {
                        photoView.setVisibility(View.GONE);
                        other.setVisibility(View.VISIBLE);
                    }
                });
            }
        });

    }
    //dialog
    private void showTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_select_photo, null);
        TextView takePic = (TextView) view.findViewById(R.id.take_pic);
        final TextView photo = (TextView) view.findViewById(R.id.photo);
        TextView look = (TextView) view.findViewById(R.id.look_big_img);
        look.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                info = PhotoView.getImageViewInfo(headImg);
                other.setVisibility(View.GONE);
                photoView.setVisibility(View.VISIBLE);
                photoView.setImageBitmap(head);
                photoView.animaFrom(info);
                dialog.dismiss();
            }
        });
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                dialog.dismiss();
            }
        });
        takePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
                startActivityForResult(intent2, 2);// 采用ForResult打开
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    private void init() {
        name = (TextView) findViewById(R.id.name);
        sex = (TextView) findViewById(R.id.sex);
        city = (TextView) findViewById(R.id.city);
        other = (LinearLayout) findViewById(R.id.other);
        photoView = (PhotoView) findViewById(R.id.photoview);
        headImg = (CircleImageView) findViewById(R.id.headimg);
        myyouhui = (LinearLayout) findViewById(R.id.second_myyouhui);
        about_us = (LinearLayout) findViewById(R.id.persion_about_us);
        setting = (LinearLayout) findViewById(R.id.persion_setting);
        persionalInfo = (LinearLayout) findViewById(R.id.persional_info);
        operat_guide = (LinearLayout) findViewById(R.id.persion_operat_guide);
        common_title_bar_left = (TextView) findViewById(R.id.common_title_bar_left);
        common_title_bar_left.setVisibility(View.VISIBLE);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("个人中心");
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    cropPhoto(data.getData());// 裁剪图片
                }
                break;
            case 2:
                if (resultCode == Activity.RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));// 裁剪图片
                }
                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);// 保存在SD卡中
                        headImg.setImageBitmap(head);// 用ImageView显示出来
                    }
                }
                break;
            case 10:
                String name = data.getStringExtra("name");
                String sex = data.getStringExtra("sex");
                if(name != null && sex != null){
                    this.name.setText("姓名:"+name);
                    this.sex.setText("性别"+sex);
                }

            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(App.IMAGE_FILE_PATH);
        if(!file.exists()){
            file.mkdirs();// 创建文件夹
        }
        String fileName = App.IMAGE_FILE_PATH + "head.jpg";// 图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 调用系统的裁剪功能
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 90);
        intent.putExtra("outputY", 90);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    @Override
    public void onBackPressed() {
        if (photoView.getVisibility() == View.VISIBLE) {
            photoView.animaTo(info, new Runnable() {
                @Override
                public void run() {
                    photoView.setVisibility(View.GONE);
                    other.setVisibility(View.VISIBLE);
                }
            });
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void success() {
        name.setText("昵称:"+App.user.getNickname());
        sex.setText("性别:"+App.user.getSex());
        city.setText("城市:"+App.user.getCity());
        head = BitmapFactory.decodeFile(App.IMAGE_FILE_PATH + "head.jpg");// 从SD卡中找头像，转换成Bitmap
        if(head != null){
            headImg.setImageBitmap(head);
        }else{
            //去服务器读
            Resources r = this.getResources();
            head = BitmapFactory.decodeResource(r, R.mipmap.ic_launcher);
            headImg.setImageBitmap(head);
        }
    }
}
